import os
import sys
import psycopg2
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from config_widget import DifficultyWindow
from project_window import ProjectWindow
from task_info_window import TaskInfoWindow
from export_window import ExportWindow
from create_excel import CreateExcel
from url_window import UrlWindow

class TabBar(QTabBar):
    def tabSizeHint(self, index):
        s = QTabBar.tabSizeHint(self, index)
        s.transpose()
        return s

    def paintEvent(self, event):
        painter =QStylePainter(self)
        opt = QStyleOptionTab()

        for i in range(self.count()):
            self.initStyleOption(opt, i)
            painter.drawControl(QStyle.CE_TabBarTabShape, opt)
            painter.save()

            s = opt.rect.size()
            s.transpose()
            r = QRect(QPoint(), s)
            r.moveCenter(opt.rect.center())
            opt.rect = r

            c = self.tabRect(i).center()
            painter.translate(c)
            painter.rotate(90)
            painter.translate(-c)
            painter.drawControl(QStyle.CE_TabBarTabLabel, opt)
            painter.restore()


class MyTableWidget(QTableWidget):
    def __init__(self):
        super(MyTableWidget, self).__init__()
        self.setRowCount(5)
        self.setColumnCount(5)
        self.setHorizontalHeaderLabels(['A','B','C'])


#资产计算表格模板
class AssetTabModel(QTableWidget):
    tab_total_Signal=pyqtSignal(str)
    def __init__(self,asset_difficulty_data,is_task):
        """
        资产计算表格模板
        :param asset_difficulty_data: {'difficulty':[A,B,C,D],'price':[A,B,C,D]}
        :param is_task:是否为任务，影响整个列
        """
        super(AssetTabModel, self).__init__()
        self.is_task=is_task
        self.h_list=['难度等级','个数(个)','单价(个/元)','合计'] if not is_task else ['难度等级','个数(个)','工时(小时)','单价(元/小时)','合计']
        print('AssetTabModelA:',asset_difficulty_data)
        self.asset_difficulty_list=asset_difficulty_data['difficulty'] #if asset_difficulty_data else []
        self.asset_price_list=asset_difficulty_data['price'] if not is_task else asset_difficulty_data['workhour']
        print('asset_price_list:',self.asset_price_list)
        # self.asset_difficulty_list.append('资产合计')
        self.setRowCount(len(self.asset_difficulty_list)+1)
        self.setColumnCount(len(self.h_list))
        self.verticalHeader().sectionDoubleClicked.connect(self._show_assets)
        self.setEditTriggers(QAbstractItemView.NoEditTriggers)

        self.init_labels()
        self.init_cell()
        self.set_difficulty(self.asset_difficulty_list)
        self.set_price(self.asset_price_list)

    def init_labels(self):
        self.setHorizontalHeaderLabels(self.h_list)
        vertical_blank=['' for i in range(self.rowCount())]
        vertical_blank[0]='资产'
        vertical_blank[-1]='资产合计'
        self.setVerticalHeaderLabels(vertical_blank)


    def init_cell(self):
        for r in range(self.rowCount()):
            for c in range(self.columnCount()):
                item=QTableWidgetItem()
                item.setText('')
                item.setBackground(QBrush(QColor('#F0FFFF')))
                item.setTextAlignment(Qt.AlignCenter)
                self.setItem(r,c,item)

    def set_difficulty(self,difficulty_list):
        """
        设置难度列
        :return:
        """
        for i in range(len(difficulty_list)):
            item=QTableWidgetItem()
            item.setText(difficulty_list[i])
            item.setTextAlignment(Qt.AlignCenter)
            item.setBackground(QBrush(QColor('#F0FFFF')))
            self.setItem(i,0,item)

    def set_price(self,price_list):
        """
        设置价格
        :param price_list:
        :return:
        """
        for i in range(len(price_list)):
            item=QTableWidgetItem()
            item.setText(price_list[i])
            item.setTextAlignment(Qt.AlignCenter)
            item.setBackground(QBrush(QColor('#F0FFFF')))
            self.setItem(i,2,item) if not self.is_task else self.setItem(i,3,item)


    def _get_shot_count_time(self,data_list):
        """
        获取传入难度镜头数据列表，得到总个数与总时长
        :param data_list:
        :return:
        """
        count=0
        all_frames=0
        fps=data_list[0]['fps']
        print('_get_shot_count_time:',fps)
        if data_list:
            count=len(data_list)
            for i in data_list:
                # fps=float(i['fps'])
                all_frames+=int(i['frame'])
        m=self.frame2minus(all_frames,fps)
        return count,m

    def count_price(self,asset_shot_info):
        """
        传入难度镜头信息数据，计算结果。顺便检测一下难度列表是不是超过，如果有难度不在所填写的难度表里，则报提示
        :param data: {'A':[data1,data2,...],'B':[data1,data2,...],...]
        :return:
        """
        if asset_shot_info:
            print('count_asset_price:',asset_shot_info.keys())
            new_difficulty=[]
            for k in asset_shot_info.keys():
                if k not in self.asset_difficulty_list and k:
                    new_difficulty.append(k)
            if new_difficulty:
                QMessageBox.information(None,'注意','资产难度{}不在所设定的难度列表里,请添加'.format(','.join(new_difficulty)))

            # for i in self.shot_difficulty_list:
            count_data={}
            for kk,v in asset_shot_info.items():
                if not kk:  #当是空难度时
                    count=len(v)
                    count_data['X'] = count

                if kk in self.shot_difficulty_list:  #当任务难度在该镜头难度列表里
                    count= len(v)
                    count_data[kk]=count
            print('count_asset_data:',count_data)
            total_price=0
            for r in range(self.rowCount()-1):  #获取难度，排除最后一列
                difficulty_item=self.item(r,0)
                difficulty=difficulty_item.text()
                price_item=self.item(r,3)
                price=price_item.text()
                count=count_data[difficulty] if difficulty in count_data.keys() else 0
                count_item=QTableWidgetItem()
                count_item.setTextAlignment(Qt.AlignCenter)
                count_item.setBackground(QBrush(QColor('#F0FFFF')))
                count_item.setText(str(count))
                self.setItem(r,1,count_item)
                per_t=count*float(price)
                per_t_item = QTableWidgetItem()
                per_t_item.setTextAlignment(Qt.AlignCenter)
                per_t_item.setBackground(QBrush(QColor('#F0FFFF')))
                per_t_item.setText(str(round(per_t,3)))
                self.setItem(r,self.columnCount()-1,per_t_item)
                total_price+=per_t

            total_item = QTableWidgetItem()
            total_item.setTextAlignment(Qt.AlignCenter)
            total_item.setBackground(QBrush(QColor('#F0FFFF')))
            total_item.setText(str(round(total_price,3)))
            print(total_price)
            print(self.rowCount(),self.columnCount())
            self.setItem(self.rowCount()-1,self.columnCount()-1,total_item)
            self.tab_total_Signal.emit(str(round(total_price,3)))
        else:
            for r in range(self.rowCount()-1):  #获取难度，排除最后一列
                difficulty_item=self.item(r,0)
                difficulty=difficulty_item.text()
                price_item=self.item(r,3)

                count_item=QTableWidgetItem()
                count_item.setTextAlignment(Qt.AlignCenter)
                count_item.setBackground(QBrush(QColor('#F0FFFF')))
                count_item.setText('0')
                time_item = QTableWidgetItem()
                time_item.setTextAlignment(Qt.AlignCenter)
                time_item.setBackground(QBrush(QColor('#F0FFFF')))
                time_item.setText('0')
                self.setItem(r,1,count_item)
                per_t_item = QTableWidgetItem()
                per_t_item.setTextAlignment(Qt.AlignCenter)
                per_t_item.setBackground(QBrush(QColor('#F0FFFF')))
                per_t_item.setText('0')
                self.setItem(r,self.columnCount()-1,per_t_item)

            total_item = QTableWidgetItem()
            total_item.setTextAlignment(Qt.AlignCenter)
            total_item.setBackground(QBrush(QColor('#F0FFFF')))
            total_item.setText('0')
            self.setItem(self.rowCount() - 1, self.columnCount() - 1, total_item)
            self.tab_total_Signal.emit('0')

    def _show_assets(self):
        """
        双击难度
        :return:
        """
        pass

    def get_excel_data(self):
        """
        获取tab信息，导出为excel的行形式
        :return:
        """
        v_list = []
        for v in range(self.rowCount()):
            v_item = self.verticalHeaderItem(v)
            text = v_item.text()
            v_list.append(text)

        h_list = ['']
        for h in range(self.columnCount()):
            h_item = self.horizontalHeaderItem(h)
            text = h_item.text()
            h_list.append(text)
        all_row_data = [h_list]

        for r in range(self.rowCount()):
            per_row_list=[v_list[r]]
            for c in range(self.columnCount()):
                c_item=self.item(r,c)
                # print(r,c)

                text=c_item.text()
                per_row_list.append(text)

            all_row_data.append(per_row_list)
        print(all_row_data)
        return all_row_data




#镜头计算表格模板
class ShotTabModel(QTableWidget):
    tab_total_Signal=pyqtSignal(str)
    def __init__(self,shot_difficulty_data,is_task):
        """
        :param asset_difficulty_list: [A,B,C,D...,资产合计]
        """
        super(ShotTabModel, self).__init__()
        self.is_task=is_task
        self.difficulty_shot_info={}  #当前项目所有镜头的难度对应镜头信息，传入得到,{'A':[data1,data2,...],'B':[data1,data2,...],...]
        # {'description': '后山环境，气浪逐渐靠近人员', 'entity_name': 'HYX01_43_036', 'eps': '01_43',
        # 'img_path': '/upload/image/proj_by/min/ca29e095a578cc5347c817fa40c225cb.png', 'frame': '35', 'fps': '25', 'shot_difficulty_level': ''}
        self.h_list=['难度等级','个数(个)','时长(分钟)','单价(个/元)','合计(元)'] if not is_task else ['难度等级','个数(个)','工时(小时)','单价(小时/元)','合计(元)']
        self.shot_difficulty_list=shot_difficulty_data['difficulty']
        self.shot_price_list=shot_difficulty_data['price'] if not is_task else shot_difficulty_data['workhour']
        self.setRowCount(len(self.shot_difficulty_list)+1)
        self.setColumnCount(len(self.h_list))

        self.verticalHeader().sectionDoubleClicked.connect(self._show_shots)
        # self.setContextMenuPolicy(Qt.CustomContextMenu)
        # self.customContextMenuRequested.connect(self.rightMenu)
        self.setEditTriggers(QAbstractItemView.NoEditTriggers)


        self.init_labels()
        self.init_cell()
        self.set_difficulty(self.shot_difficulty_list)
        self.set_price(self.shot_price_list)

    # def rightMenu(self):
    #     mainMenu=QMenu()
    #     detail_action=QAction('查看所选')
    #     mainMenu.addAction(save_action)
    #     mainMenu.exec_(QCursor.pos())

    def init_labels(self):
        self.setHorizontalHeaderLabels(self.h_list)
        vertical_blank=['' for i in range(self.rowCount())]
        vertical_blank[0]='镜头'
        vertical_blank[-1]='镜头合计'

        self.setVerticalHeaderLabels(vertical_blank)


    def init_cell(self):
        for r in range(self.rowCount()):
            for c in range(self.columnCount()):
                item=QTableWidgetItem()
                item.setText('')
                item.setBackground(QBrush(QColor('#F0FFFF')))
                item.setTextAlignment(Qt.AlignCenter)
                self.setItem(r,c,item)

    def set_difficulty(self,difficulty_list):
        """
        设置难度列
        :return:
        """
        #self.difficulty_list=difficulty_list
        for i in range(len(difficulty_list)):
            item=QTableWidgetItem()
            item.setText(difficulty_list[i])
            item.setTextAlignment(Qt.AlignCenter)
            item.setBackground(QBrush(QColor('#F0FFFF')))
            self.setItem(i,0,item)


    def set_price(self,price_list):
        """
        设置价格
        :param price_list:
        :return:
        """
        for i in range(len(price_list)):
            item=QTableWidgetItem()
            item.setText(price_list[i])
            item.setTextAlignment(Qt.AlignCenter)
            item.setBackground(QBrush(QColor('#F0FFFF')))
            # self.setItem(i,2,item) if not self.is_task else self.setItem(i,3,item)
            self.setItem(i, 3, item)

    def frame2minus(self,frame,fps):
        """
        将帧转成分钟
        :param frame:
        :return:
        """
        s=float(frame)/float(fps)
        m=s/60
        return m


    def _get_shot_count_time(self,data_list):
        """
        获取传入难度镜头数据列表，得到总个数与总时长
        :param data_list:
        :return:
        """
        count=0
        all_frames=0
        fps=data_list[0]['fps']
        print('_get_shot_count_time:',fps)
        if data_list:
            count=len(data_list)
            for i in data_list:
                # fps=float(i['fps'])
                all_frames+=int(i['frame'])
        m=self.frame2minus(all_frames,fps)
        return count,m

    def count_price(self,difficulty_shot_info):
        """
        传入难度镜头信息数据，计算结果。顺便检测一下难度列表是不是超过，如果有难度不在所填写的难度表里，则报提示
        :param data: {'A':[data1,data2,...],'B':[data1,data2,...],...]
        :return:
        """
        if difficulty_shot_info:
            self.difficulty_shot_info=difficulty_shot_info
            print('count_price:',difficulty_shot_info.keys())
            new_difficulty=[]
            for k in difficulty_shot_info.keys():
                if k not in self.shot_difficulty_list and k:
                    new_difficulty.append(k)
            if new_difficulty:
                QMessageBox.information(None,'注意','镜头难度{}不在所设定的难度列表里,请添加'.format(','.join(new_difficulty)))

            # for i in self.shot_difficulty_list:
            count_data={}
            for kk,v in difficulty_shot_info.items():
                if not kk:  #当是空难度时
                    count,m=self._get_shot_count_time(v)
                    count_data['X'] = (count,m)

                if kk in self.shot_difficulty_list:  #当任务难度在该镜头难度列表里
                    count, m = self._get_shot_count_time(v)
                    count_data[kk]=(count,m)
            print('count_data:',count_data)
            total_price=0
            for r in range(self.rowCount()-1):  #获取难度，排除最后一列
                difficulty_item=self.item(r,0)
                difficulty=difficulty_item.text()
                price_item=self.item(r,3)
                price=price_item.text()
                count,m=count_data[difficulty] if difficulty in count_data.keys() else (0,0)
                count_item=QTableWidgetItem()
                count_item.setTextAlignment(Qt.AlignCenter)
                count_item.setBackground(QBrush(QColor('#F0FFFF')))
                count_item.setText(str(count))
                time_item = QTableWidgetItem()
                time_item.setTextAlignment(Qt.AlignCenter)
                time_item.setBackground(QBrush(QColor('#F0FFFF')))
                time_item.setText(str(round(m,3)))
                self.setItem(r,1,count_item)
                self.setItem(r,2,time_item)
                per_t=count*m*float(price)
                per_t_item = QTableWidgetItem()
                per_t_item.setTextAlignment(Qt.AlignCenter)
                per_t_item.setBackground(QBrush(QColor('#F0FFFF')))
                per_t_item.setText(str(round(per_t,3)))
                self.setItem(r,self.columnCount()-1,per_t_item)
                total_price+=per_t

            total_item = QTableWidgetItem()
            total_item.setTextAlignment(Qt.AlignCenter)
            total_item.setBackground(QBrush(QColor('#F0FFFF')))
            total_item.setText(str(round(total_price,3)))
            print(total_price)
            print(self.rowCount(),self.columnCount())
            self.setItem(self.rowCount()-1,self.columnCount()-1,total_item)
            self.tab_total_Signal.emit(str(round(total_price,3)))
        else:
            for r in range(self.rowCount()-1):  #获取难度，排除最后一列
                difficulty_item=self.item(r,0)
                difficulty=difficulty_item.text()
                price_item=self.item(r,3)
                price=price_item.text()
                #count,m=count_data[difficulty] if difficulty in count_data.keys() else (0,0)
                count_item=QTableWidgetItem()
                count_item.setTextAlignment(Qt.AlignCenter)
                count_item.setBackground(QBrush(QColor('#F0FFFF')))
                count_item.setText('0')
                time_item = QTableWidgetItem()
                time_item.setTextAlignment(Qt.AlignCenter)
                time_item.setBackground(QBrush(QColor('#F0FFFF')))
                time_item.setText('0')
                self.setItem(r,1,count_item)
                self.setItem(r,2,time_item)
                #per_t=count*m*float(price)
                per_t_item = QTableWidgetItem()
                per_t_item.setTextAlignment(Qt.AlignCenter)
                per_t_item.setBackground(QBrush(QColor('#F0FFFF')))
                per_t_item.setText('0')
                self.setItem(r,self.columnCount()-1,per_t_item)

            total_item = QTableWidgetItem()
            total_item.setTextAlignment(Qt.AlignCenter)
            total_item.setBackground(QBrush(QColor('#F0FFFF')))
            total_item.setText('0')
            self.setItem(self.rowCount() - 1, self.columnCount() - 1, total_item)
            self.tab_total_Signal.emit('0')



    def _show_shots(self,index):
        """
        双击难度
        :return:
        """

        if index!=self.rowCount()-1:
            print('_show_shots:', index)
            difficulty=self.item(index,0).text()
            if difficulty in self.difficulty_shot_info.keys():
                shot_data_list=self.difficulty_shot_info[difficulty]
                self.taskInfoWindow=TaskInfoWindow(shot_data_list)
                self.taskInfoWindow.show()

    def get_excel_data(self):
        """
        获取tab信息，导出为excel的行形式
        :return:
        """
        v_list = []
        for v in range(self.rowCount()):
            v_item = self.verticalHeaderItem(v)
            text = v_item.text()
            v_list.append(text)

        h_list = ['']
        for h in range(self.columnCount()):
            h_item = self.horizontalHeaderItem(h)
            text = h_item.text()
            h_list.append(text)
        all_row_data = [h_list]

        for r in range(self.rowCount()):
            per_row_list=[v_list[r]]
            for c in range(self.columnCount()):
                c_item=self.item(r,c)
                # print(r,c)

                text=c_item.text()
                per_row_list.append(text)

            all_row_data.append(per_row_list)
        print(all_row_data)
        return all_row_data


# #项目tab
#
# class AssetTab(QTableWidget):
#     def __init__(self,asset_difficulty_list):
#         """
#
#         :param asset_difficulty_list: [A,B,C,D...,资产合计]
#         """
#         super(AssetTab, self).__init__()
#         self.h_list=['资产','难度等级','个数(个)','单价(个/元)','合计']
#         self.asset_difficulty_list=asset_difficulty_list
#         self.setRowCount(len(asset_difficulty_list))
#         self.setColumnCount(len(self.h_list))
#
#         self.init_labels()
#         self.init_cell()
#
#     def init_labels(self):
#         self.setHorizontalHeaderLabels(self.h_list)
#         vertical_blank=['' for i in range(self.rowCount())]
#         vertical_blank[0]='资产'
#         vertical_blank[-1]='资产合计'
#         self.setVerticalHeaderLabels(vertical_blank)
#
#
#     def init_cell(self):
#         for r in range(self.rowCount()):
#             for c in range(self.columnCount()):
#                 item=QTableWidgetItem()
#                 item.setText('')
#                 item.setTextAlignment(Qt.AlignCenter)
#                 self.setItem(r,c,item)
#
# class ShotTab(QTableWidget):
#     def __init__(self,shot_difficulty_list):
#         """
#
#         :param asset_difficulty_list: [A,B,C,D...,资产合计]
#         """
#         super(ShotTab, self).__init__()
#         self.h_list=['镜头','难度等级','个数(个)','时长(分钟/元)','单价(个/元)','合计']
#         self.shot_difficulty_list=shot_difficulty_list
#         self.setRowCount(len(shot_difficulty_list))
#         self.setColumnCount(len(self.h_list))
#
#         self.init_labels()
#         self.init_cell()
#
#     def init_labels(self):
#         self.setHorizontalHeaderLabels(self.h_list)
#         vertical_blank=['' for i in range(self.rowCount())]
#         vertical_blank[0]='镜头'
#         vertical_blank[-1]='镜头合计'
#         self.setVerticalHeaderLabels(vertical_blank)
#
#
#     def init_cell(self):
#         for r in range(self.rowCount()):
#             for c in range(self.columnCount()):
#                 item=QTableWidgetItem()
#                 item.setText('')
#                 self.setItem(r,c,item)


class ProjectInWidgetTab(QTabWidget):

    def __init__(self,data,show_total):
        super(ProjectInWidgetTab, self).__init__()
        self.data=data
        self.asset_price=0
        self.show_total=show_total  #该tab窗口显示的总价格label
        print('ProjectInWidgetTab:',self.data)
        self.assetTab=AssetTabModel(data['Asset'],0)
        self.assetTab.tab_total_Signal.connect(self._asset_tab_total)
        self.shotTab = ShotTabModel(data['Shot'],0)
        self.shotTab.tab_total_Signal.connect(self._shot_tab_total)
        self.addTab(self.assetTab, QIcon("zoom.png"), '资产')
        self.addTab(self.shotTab, QIcon("zoom.png"), '镜头')

    def _asset_tab_total(self,tab_total):
        self.asset_price=float(tab_total)
        #self.asset_price=1111111

    def _shot_tab_total(self,tab_total):
        all_price=self.asset_price+float(tab_total)
        self.show_total.setText(str(all_price))

    def set_tab_price(self,data):
        shot_data = data['Shot']
        asset_data = data['Asset']
        self.assetTab.set_price(asset_data)
        self.shotTab.set_price(shot_data)

    def prsing_asset_data(self,data):
        """
        解析从数据库中读取asset的数据
        :param data:   [{'description': '修灯穿帮（看图片备注字段）', 'entity_name': 'PH30_011_001', 'eps': '30sPH',
                        'img_path': '/upload/image/proj_by/min/aecf02bb63a56cea8c2a2b521363314b.png', 'frame': '33',
                         'shot_difficulty_level': 'D'}, {..},...]
        :return: {'A':[data1,data2,...],'B':[data1,data2,...],...]  以难度为key的所有镜头列表的集合
        """
        difficulty_shot_info={}
        if data:
            for i in data:
                asset_difficulty_level=i['asset_difficulty_level']
                if asset_difficulty_level not in difficulty_shot_info.keys():
                    difficulty_shot_info[asset_difficulty_level]=[i]
                else:
                    difficulty_shot_info[asset_difficulty_level].append(i)

        return difficulty_shot_info


    def prsing_shot_data(self,data):
        """
        解析从数据库中读取shot的数据
        :param data:   [{'description': '修灯穿帮（看图片备注字段）', 'entity_name': 'PH30_011_001', 'eps': '30sPH',
                        'img_path': '/upload/image/proj_by/min/aecf02bb63a56cea8c2a2b521363314b.png', 'frame': '33',
                         'shot_difficulty_level': 'D'}, {..},...]
        :return: {'A':[data1,data2,...],'B':[data1,data2,...],...]  以难度为key的所有镜头列表的集合
        """
        difficulty_shot_info={}
        if data:
            for i in data:
                shot_difficulty_level=i['shot_difficulty_level']
                if shot_difficulty_level not in difficulty_shot_info.keys():
                    difficulty_shot_info[shot_difficulty_level]=[i]
                else:
                    difficulty_shot_info[shot_difficulty_level].append(i)

        return difficulty_shot_info


    def count_data(self,asset_data_list,shot_data_list):
        """
        输入解析后的数据，并计算结果
        :param data:    [{'description': '修灯穿帮（看图片备注字段）', 'entity_name': 'PH30_011_001', 'eps': '30sPH',
                        'img_path': '/upload/image/proj_by/min/aecf02bb63a56cea8c2a2b521363314b.png', 'frame': '33',
                         'shot_difficulty_level': 'D'}, {..},...]
        :return:
        """

        difficulty_asset_info = self.prsing_asset_data(asset_data_list)
        self.assetTab.count_price(difficulty_asset_info)
        difficulty_shot_info=self.prsing_shot_data(shot_data_list)
        self.shotTab.count_price(difficulty_shot_info)

    def get_all_tab_data(self):
        """
        获取当前界面所欲
        :return:
        """
        asset_tab_data=self.assetTab.get_excel_data()
        blank_data=['' for i in range(8)]
        shot_tab_data=self.shotTab.get_excel_data()
        all_tab_data=asset_tab_data+[blank_data]+[blank_data]+shot_tab_data
        return all_tab_data

class ProjectWidget(QWidget):
    """
    项目Widget,里面有资产、镜头tab,还有合计
    """
    def __init__(self,price_data):
        super(ProjectWidget, self).__init__()
        self.main_layout=QVBoxLayout()
        self.price_data=price_data
        print('ProjectWidget:',price_data)

        self.btn_style='''QPushButton{color:black}
                                  QPushButton:hover{color:red}
                                  QPushButton{background-color:#FFDEAD}
                                  QPushButton{border:2px}
                                  QPushButton{border-radius:3px}
                                  QPushButton{padding:1px 1px}'''
        self.count_layout=QHBoxLayout()
        self.count_label=QLabel('项目报价合计:')
        self.count_value_label=QLabel('0')
        self.count_value_label.setTextInteractionFlags(Qt.TextSelectableByMouse)
        self.count_layout.addWidget(self.count_label)
        self.count_layout.addWidget(self.count_value_label)
        self.export_layout=QHBoxLayout()
        self.export_layout.setContentsMargins(50,0,0,0)
        self.export_btn=QPushButton('导出Excel')
        self.export_btn.setStyleSheet(self.btn_style)
        self.export_btn.clicked.connect(self._export_excel)
        self.export_layout.addWidget(self.export_btn)
        self.count_layout.addLayout(self.export_layout)
        self.projectInWidget=ProjectInWidgetTab(self.price_data,self.count_value_label)
        self.main_layout.addWidget(self.projectInWidget)
        self.main_layout.addLayout(self.count_layout)
        # self.main_layout.addLayout(self.cost_layout)
        # self.main_layout.addLayout(self.diff_layout)
        self.setLayout(self.main_layout)

    def set_project_table_price(self,data):
        """
        设置项目里的assetTab与shotTab的值
        :param data:
        :return:
        """
        if data:
            self.projectInWidget.set_tab_price(data)

    def get_cost(self,asset_data_list,shot_data_list):
        """
        通过读取到的镜头数据信息。输入到表格中并计算结果,现在还没有资产，只有镜头
        :param data:[{'description': '修灯穿帮（看图片备注字段）', 'entity_name': 'PH30_011_001', 'eps': '30sPH',
                        'img_path': '/upload/image/proj_by/min/aecf02bb63a56cea8c2a2b521363314b.png', 'frame': '33',
                         'shot_difficulty_level': 'D'}, {..},...]
        :return:
        """
        self.projectInWidget.count_data(asset_data_list,shot_data_list)

    def _export_excel(self):
        self.export_window=ExportWindow()
        self.export_window.path_Signal.connect(self._export)
        self.export_window.show()

    def _export(self,path):
        all_tab_data=self.projectInWidget.get_all_tab_data()
        print('_export:',all_tab_data)
        create_excel=CreateExcel()
        try:
            create_excel.create('项目报价合计',all_tab_data,path)
            self.url_window = UrlWindow('转换', '转换成功', path)
            self.url_window.show()
        except Exception as _export_ERR:
            print(str(_export_ERR))

#总树叶tab页不需要tab,只需要widget
# class ProjectTab(QTabWidget):
#     """
#     总树叶项目tab页，里面项目Widget
#     """
#     def __init__(self):
#         super(ProjectTab, self).__init__()
#         #self.asset_tab=AssetTab(['A','B','C','D','E'])
#         self.project_widget=ProjectWidget()
#         self.addTab(self.project_widget,QIcon("zoom.png"),'项目')


#美术tab

class MInWidgetTab(QTabWidget):
    """
    美术tab页，包含
    """
    def __init__(self,data):
        super(MInWidgetTab, self).__init__()
        print('MInWidgetTab:',data)
        self.mp_tab=AssetTabModel(data['mp'],1)
        self.cpt_c_tab=AssetTabModel(data['cpt_c'],1)
        self.cpt_s_tab = AssetTabModel(data['cpt_s'],1)
        self.addTab(self.mp_tab, QIcon("zoom.png"), 'mp')
        self.addTab(self.cpt_c_tab, QIcon("zoom.png"), 'cpt_c')
        self.addTab(self.cpt_s_tab, QIcon("zoom.png"), 'cpt_s')




class MWidget(QWidget):
    """
    美术widget,里面有mp,cpt_c,cpt_s各tab页以及合计栏
    """
    def __init__(self,mdata):
        super(MWidget, self).__init__()
        self.mdata=mdata
        self.main_layout=QVBoxLayout()
        self.m_intab=MInWidgetTab(self.mdata)
        self.main_layout.addWidget(self.m_intab)
        self.count_layout=QHBoxLayout()
        self.count_label=QLabel('美术合计:')
        self.count_value_label=QLabel('')
        self.count_layout.addWidget(self.count_label)
        self.count_layout.addWidget(self.count_value_label)
        self.main_layout.addLayout(self.count_layout)
        self.setLayout(self.main_layout)


# class MTab(QTabWidget):
#     """
#     总树叶，美术tab页面板,里面有MpWidget
#     """
#     def __init__(self):
#         super(MTab, self).__init__()
#         self.mwidget=MWidget()
#         self.addTab(self.mwidget, QIcon("zoom.png"), '美术')






class VerticalTab(QTabWidget):
    def __init__(self):
        super(VerticalTab, self).__init__()
        self.CONFIG_PATH=os.path.join(os.path.dirname(__file__),'config')
        self.project_config_path=os.path.join(self.CONFIG_PATH,'project_config')
        self.pipeline_config_path=os.path.join(self.CONFIG_PATH,'pipeline_config')

        self.setTabBar(TabBar(self))
        self.setTabPosition(QTabWidget.West)
        #self.asset_tab=AssetTab(['A','B','C','D','E'])
        #self.addTab(self.asset_tab,QIcon("zoom.png"),'项目')
        # self.project_tab=ProjectTab()
        self.price_data=self.get_price_data()
        self.project_widget=ProjectWidget(self.price_data)  #含项目的tab页
        self.addTab(self.project_widget,QIcon("zoom.png"),'项目')

        self.all_pipeline_data=self.get_all_pipeline_data()
        self.mwidget=MWidget(self.all_pipeline_data['M'])
        self.addTab(self.mwidget,QIcon("zoom.png"),'美术')

        # self.init_project_data()

    def get_price_data(self):
        """
        获取项目的难度报价数据
        :return:
        """
        data={}
        try:
            with open(self.project_config_path,'r',encoding='utf8') as r:
                data=eval(r.read())
            #print('get_price_data:',data)
        except Exception as get_price_data_ERR:
            QMessageBox.information(self,'获取价格表失败',str(get_price_data_ERR))
        return data

    def get_all_pipeline_data(self):
        """
        获取所有阶段信息，现在也在本地
        :return:
        """
        data={}
        try:
            with open(self.pipeline_config_path, 'r', encoding='utf8') as r:
                data = eval(r.read())
            # print('get_price_data:',data)
        except Exception as get_price_data_ERR:
            QMessageBox.information(self, '获取价格表失败', str(get_price_data_ERR))
        return data

    def count_project_widget(self,asset_data_list,shot_data_list):
        """
        传入数据库读取的镜头信息，生成镜头数据,现阶段还没有资产，之后可以加入资产信息
        :param data:[{'description': '修灯穿帮（看图片备注字段）', 'entity_name': 'PH30_011_001', 'eps': '30sPH',
                        'img_path': '/upload/image/proj_by/min/aecf02bb63a56cea8c2a2b521363314b.png', 'frame': '33',
                         'shot_difficulty_level': 'D'}, {..},...]
        :return:
        """
        self.project_widget.get_cost(asset_data_list,shot_data_list)


class ProjectBudget(QWidget):

    def __init__(self):
        super(ProjectBudget, self).__init__()
        self.CONFIG_PATH=os.path.join(os.path.dirname(__file__),'config')
        self.project_config_path=os.path.join(self.CONFIG_PATH,'project_config')
        self.pipeline_config_path=os.path.join(self.CONFIG_PATH,'pipeline_config')
        self.db_config_path=os.path.join(self.CONFIG_PATH,'db_config')
        self.IMG_PATH=os.path.join(os.path.dirname(__file__),'img')

        self.project_data=''  #选择的项目信息 {'color': '#3E9EFF', 'database': 'proj_by', 'entity_name': 'HYX', 'full_name': '皓衣行'}

        self.icon = QIcon()
        icon_path = os.path.join(self.IMG_PATH,'bu.png')
        self.icon.addPixmap(QPixmap(icon_path))
        self.setWindowIcon(self.icon)
        self.btn_style='''QPushButton{color:black}
                                  QPushButton:hover{color:red}
                                  QPushButton{background-color:#FFDEAD}
                                  QPushButton{border:2px}
                                  QPushButton{border-radius:3px}
                                  QPushButton{padding:1px 1px}'''
        self.big_font=QFont('',20,65)
        self.setWindowTitle('项目预算')
        self.setMinimumWidth(700)
        self.setMinimumHeight(800)
        self.main_layout=QVBoxLayout()
        self.main_layout.setSpacing(10)
        self.label_layout=QHBoxLayout()
        self.label_layout.setAlignment(Qt.AlignCenter)
        self.tool_layout=QHBoxLayout()
        self.project_budget_label=QLabel('项目预算表')
        self.project_budget_label.setFont(self.big_font)
        self.project_layout=QHBoxLayout()
        self.project_layout.setAlignment(Qt.AlignLeft)
        self.project_select_label=QLabel('项目:')
        self.project_select_btn=QPushButton('- -')
        self.project_select_btn.setStyleSheet(self.btn_style)
        self.project_select_btn.clicked.connect(self._select_project)
        self.project_layout.addWidget(self.project_select_label)
        self.project_layout.addWidget(self.project_select_btn)
        self.fps_layout=QHBoxLayout()
        self.fps_layout.setContentsMargins(10,0,500,0)
        self.fps_label=QLabel('帧速率:')
        self.fps_edit=QLineEdit()
        self.fps_edit.setFrame(False)
        self.fps_edit.setAlignment(Qt.AlignLeft)
        self.fps_edit.setMaximumWidth(50)
        self.fps_layout.addWidget(self.fps_label)
        self.fps_layout.addWidget(self.fps_edit)
        self.config_layout=QHBoxLayout()
        self.config_layout.setAlignment(Qt.AlignRight)
        self.db_btn=QPushButton('载入数据')
        self.db_btn.setStyleSheet(self.btn_style)
        self.db_btn.clicked.connect(self._get_data)
        self.config_btn=QPushButton('配置难度')
        self.config_btn.setStyleSheet(self.btn_style)
        self.config_btn.clicked.connect(self._open_config_window)
        self.config_layout.addWidget(self.db_btn)
        self.config_layout.addWidget(self.config_btn)
        self.tool_layout.addLayout(self.project_layout)
        self.tool_layout.addLayout(self.fps_layout)
        self.tool_layout.addLayout(self.config_layout)

        self.label_layout.addWidget(self.project_budget_label)
        self.vertical_tab=VerticalTab()

        self.budget_layout=QHBoxLayout()
        self.budget_layout.setAlignment(Qt.AlignCenter)
        self.budget_label=QLabel('报价合计:')
        self.budget_value_label=QLabel('0')
        self.budget_layout.addWidget(self.budget_label)
        self.budget_layout.addWidget(self.budget_value_label)
        self.cost_layout=QHBoxLayout()
        self.cost_layout.setAlignment(Qt.AlignCenter)
        self.cost_label=QLabel('成本合计:')
        self.cost_value_label=QLabel('0')
        self.cost_layout.addWidget(self.cost_label)
        self.cost_layout.addWidget(self.cost_value_label)
        self.diff_layout=QHBoxLayout()
        self.diff_layout.setContentsMargins(0,0,0,20)
        self.diff_layout.setAlignment(Qt.AlignCenter)
        self.diff_label=QLabel('  差 额 :')
        self.diff_value_label=QLabel('0')
        self.diff_layout.addWidget(self.diff_label)
        self.diff_layout.addWidget(self.diff_value_label)

        self.main_layout.addLayout(self.label_layout)
        self.main_layout.addLayout(self.tool_layout)
        self.main_layout.addWidget(self.vertical_tab)
        self.main_layout.addLayout(self.budget_layout)
        self.main_layout.addLayout(self.cost_layout)
        self.main_layout.addLayout(self.diff_layout)

        self.setLayout(self.main_layout)


    def _select_project(self):
        """
        打开项目选择窗口
        :return:
        """
        try:
            self.project_window=ProjectWindow(self.icon,self.IMG_PATH)
            self.project_window.database_Signal.connect(self._get_project_info)
            self.project_window.show()
        except Exception as open_project_window_ERR:
            print(str(open_project_window_ERR))

    def _get_project_info(self,data):
        if data:
            print('_get_project_info:',data)
            self.project_data=data
            self.project_select_btn.setText(data['full_name']+'('+data['entity_name']+')')
            self.fps_edit.setText(data['frame_rate'])

    def _get_data(self):
        """
        从数据库中获取数据
        :return:
        """
        if self.project_data:
            # print('project_data:',self.project_data)
            db={}
            asset_data_list = [] #资产信息列表
            shot_data_list=[]  #镜头信息列表
            shot_difficulty_level_list=[]

            try:
                with open(self.db_config_path,'r',encoding='utf8') as r:
                    db=eval(r.read())
                if db:
                    print('db:',db)
                    time_connect=psycopg2.connect(database=db['db'],user=db['user'],password=db['password'],host=db['ip'],port=db['port'])
                    time_cursor=time_connect.cursor()
                    shot_select_sql="select description,entity_name,eps,img_path,frame,shot_difficulty_level from timeaxis.r_shot where cg_id similar to '({}%)' ".format(self.project_data['database'])
                    asset_select_sql="select description,entity_name,eps,img_path,frame,shot_difficulty_level from timeaxis.r_asset where cg_id similar to '({}%)' ".format(self.project_data['database']) #资产难度暂时没有录入，留个位置
                    try:
                        time_cursor.execute(shot_select_sql)
                        result = time_cursor.fetchall()
                        if result:
                            for i in result:
                                data={}
                                data['description']=i[0]
                                data['entity_name'] = i[1]
                                data['eps'] = i[2]
                                data['img_path'] = i[3]
                                data['frame']=i[4]
                                data['fps']=self.fps_edit.text()  #注意这里就变成了fps
                                data['shot_difficulty_level'] = i[5]
                                if i[5] not in shot_difficulty_level_list:
                                    shot_difficulty_level_list.append(i[5])
                                shot_data_list.append(data)

                            if shot_data_list:
                                self.vertical_tab.count_project_widget(asset_data_list,shot_data_list)

                    except Exception as select_sql_ERR:
                        print(str(select_sql_ERR))
                    finally:
                        time_connect.close()

            except Exception as _get_data_ERR:
                QMessageBox.information(self,'获取数据失败',str(_get_data_ERR))
            print('shot_data_list:',shot_data_list)
            #print('shot_difficulty_level_list:',shot_difficulty_level_list)
            return shot_data_list

        else:
            QMessageBox.information(self,'提示','请先选择项目')




    def _open_config_window(self):
        self.config_window=DifficultyWindow()
        self.config_window.show()




if __name__ == '__main__':
    app=QApplication(sys.argv)
    p=ProjectBudget()
    p.show()
    sys.exit(app.exec_())

